﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
#if DEBUG
using System.Diagnostics;
#endif // #if DEBUG
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using FRL.DebtChased.Extensions;
using FRL.DebtChased.Repository;
using FRL.DebtChased.Silverlight.Library;
using FRL.DebtChased.Silverlight.Library.RichContentService;

namespace FRL.DebtChased.CommBodyEditor
{

	/// <summary>
	/// Declaration of CommBodyEditCtrl class
	/// Cointrol for editing the details and body of a comm body
	/// </summary>
	public partial class CommBodyEditCtrl : UserControl
	{

		/////////////////////////////////////////////////////////////
		// Attributes

		private int m_iCommBodyId = 0;

		private Definitions.eCommBodyType m_commBodyType = Definitions.eCommBodyType.NotSet;

		private bool m_bContentSaved = false;

		/////////////////////////////////////////////////////////////
		// Construction

		public CommBodyEditCtrl()
		{

			// Load xaml resources
			InitializeComponent();

		}

		/////////////////////////////////////////////////////////////
		// Event Handlers

		private void butClose_Click(object sender, RoutedEventArgs e)
		{

			// Inform the main window
			MainPage.Singleton.CloseCommBodyCtrl(m_bContentSaved);

		}

		private void butSave_Click(object sender, RoutedEventArgs e)
		{

			// Get control values
			string strName = txtName.Text;
			int iCommTemplateId = (cboTemplate.SelectedItem as ComboBoxObject).ItemData;
			string strContent = txtBody.Text;

			// Validate the controls
			List<string> ErrorList = null;
			if(strName.Length < 2)
				Extensions.Extensions.SafeAddString(ref ErrorList,"Body name must be 2 characters.");
			if ((m_commBodyType == Definitions.eCommBodyType.Email) || (m_commBodyType == Definitions.eCommBodyType.Letter))
			{
				if (iCommTemplateId == 0)
					Extensions.Extensions.SafeAddString(ref ErrorList, "Select a template.");
			}
			if (strContent.Length < 10)
				Extensions.Extensions.SafeAddString(ref ErrorList, "Body name must be 10 characters.");
			if (ErrorList != null)
			{
				MessageBoxes.PopupErrors(ErrorList);
				return;
			}

			// Get the body into an object
			CommBodyTransport cbt = new CommBodyTransport();
			cbt.CommBodyId = m_iCommBodyId;
			cbt.CommBodyType = (int)m_commBodyType;
			cbt.CommTemplateId = iCommTemplateId;
			cbt.Name = strName;
			cbt.Subject = txtSubject.Text;
			cbt.Content = strContent;
			cbt.SectionList = _getSectionList(cbt.Content, cbt.Subject);

			// Option to save
			if (MessageBoxes.PopupOption("Save comm body?"))
			{

				// Show hourglass
				MainPage.Singleton.hourglassCtrl.IncShowCount(true);

				// Load the comm-body summary list
				RichContentServiceClient proxy = new RichContentServiceClient();
				proxy.SetCommBodyCompleted +=new EventHandler<SetCommBodyCompletedEventArgs>(proxy_SetCommBodyCompleted);
				proxy.Endpoint.Address = ExtensionsForSilverlight.CreateDebtChasedEndpoint();
				proxy.SetCommBodyAsync(cbt);

			}

		}

		private void ExpandButton_Click(object sender, EventArgs e)
		{

			// If panel needs expanding...
			if (ctrlFieldPicker.Width < ctrlFieldPicker.MaxWidth)
			{

				// Expand panel
				AnimShowFieldFinder.Begin();

			}
			else
			{

				// Contract panel
				AnimHideFieldFinder.Begin();

			}

		}

		void  proxy_SetCommBodyCompleted(object sender, SetCommBodyCompletedEventArgs e)
		{

			// Hide hourglass
			MainPage.Singleton.hourglassCtrl.IncShowCount(false);

			// Get the result
			if (e.Error != null)
				MessageBoxes.PopupMessage(e.Error.Message);
			else if (e.Result != null)
				MessageBoxes.PopupMessage(e.Result);
			else
			{

				// Upodate flag
				m_bContentSaved = true;

				// Update id
				if (m_iCommBodyId == 0)
				{
#if DEBUG
					Debug.Assert(e.commBodyTransport.CommBodyId != 0);
#endif // #if DEBUG
					m_iCommBodyId = e.commBodyTransport.CommBodyId;
				}
				else
				{
#if DEBUG
					Debug.Assert(m_iCommBodyId == e.commBodyTransport.CommBodyId);
#endif // #if DEBUG
				}

			}

			// Setup controls
			_setupControls();

		}

		/////////////////////////////////////////////////////////////
		// Operations

		public void InsertField(string strFieldName)
		{

			// Update the body
			if (txtBody.SelectionStart == txtBody.Text.Length)
				txtBody.Text += StufferDefinitions.AddSyntaxToField(strFieldName);
			else
				txtBody.Text = string.Format("{0}{1}{2}",
					txtBody.Text.Substring(0, txtBody.SelectionStart),
					StufferDefinitions.AddSyntaxToField(strFieldName),
					txtBody.Text.Substring(txtBody.SelectionStart + txtBody.SelectionLength)
				);

			// Focus back on textbox
			txtBody.Focus();

		}

		public ObservableCollection<string> _getSectionList( params string[] strArray )
		{

			// Declare return variable
			ObservableCollection<string> Ftmp = new ObservableCollection<string>();

			// Loop through each string, looking for sections
			for (int iParam = 0; iParam < strArray.Length; iParam++)
			{

				// Find section
				int iPos = 0;
				while (true)
				{

					// Find next section
					iPos = strArray[iParam].IndexOf("<%",iPos);
					if (iPos == -1)
						break;
					int iPos2 = strArray[iParam].IndexOf("%>",iPos);
					if( (iPos2 - iPos) < 50 )
					{
						string strSection;
						if (strArray[iParam][iPos + 2] == '/')
							strSection = strArray[iParam].Substring(iPos+3,iPos2 - iPos-3);
						else
							strSection = strArray[iParam].Substring(iPos+2,iPos2 - iPos-2);
						if (!Ftmp.Contains(strSection))
							Ftmp.Add(strSection);
					}

					// Move on
					iPos = iPos2;

				} // while-loop

			}

			// Return variable
			return Ftmp;

		}

		public void SupportingDataLoaded()
		{

			// Called after plug-in has loaded support data

		}

		public void Set(CommBodyTransport cbt)
		{

			// Update member variables
			m_iCommBodyId = cbt.CommBodyId;
			m_commBodyType = (Definitions.eCommBodyType) cbt.CommBodyType;

			// Set title 
			tbTitle.Text = string.Format("Comm Body {0}", ((Definitions.eCommBodyType)cbt.CommBodyType).ToString());

			// Load suitable templates
			cboTemplate.Items.Clear();
			cboTemplate.Items.Add(new ComboBoxObject(Definitions.NotSet, 0, null));
			if (cbt.CommBodyType == (int)Definitions.eCommBodyType.SMS)
			{

				// No templates required
				cboTemplate.SelectedIndex = 0;				

			}
			else
			{

				// Load template control
				foreach (CommTemplateTransport ctt in CachedData.Singleton.CommTemplateList)
				{
					if (
						(
							(ctt.CommTemplateType == (int)Definitions.eCommTemplateType.Email)
							&&
							(cbt.CommBodyType == (int)Definitions.eCommBodyType.Email)
						)
						||
						(
							(ctt.CommTemplateType == (int)Definitions.eCommTemplateType.Letter)
							&&
							(cbt.CommBodyType == (int)Definitions.eCommBodyType.Letter)
						)
					)
						cboTemplate.Items.Add(new ComboBoxObject(ctt.Name, ctt.CommTemplateId, ctt));
				}

				// Select template
				ComboBoxObject.SelectByItemData(cboTemplate, cbt.CommTemplateId);

			}

			// Set controls
			txtName.Text = cbt.Name ?? string.Empty;
			tbType.Text = ((Definitions.eCommBodyType)cbt.CommBodyType).ToString();
			txtBody.Text = cbt.Content ?? string.Empty;

			// Set subject for emails
			if (cbt.CommBodyType == (int)Definitions.eCommBodyType.Email)
				txtSubject.Text = cbt.Subject ?? string.Empty;

			// Setup controls
			_setupControls();

		}

		private void _setupControls()
		{

			// Show/hide controls
			cboTemplate.Visibility = (m_commBodyType != Definitions.eCommBodyType.SMS) ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
			tbTemplate.Visibility = cboTemplate.Visibility;

			txtSubject.Visibility = (m_commBodyType == Definitions.eCommBodyType.Email) ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
			tbSubject.Visibility = txtSubject.Visibility;

		}

	}

}
